package leetcode.D100.T8;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2021-08-08 20:46:29 星期日
 */

public class Solution {
    public int myAtoi(String s) {
        boolean flag = true;
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while(i < s.length()) {
            if(s.charAt(i) != ' ') {
                break;
            }
            ++i;
        }
        if(i >= s.length()) {
            return 0;
        }
        if(s.charAt(i) == '+') {
            ++i;
        } else if(s.charAt(i) == '-') {
            flag = false;
            ++i;
        } else if(s.charAt(i) < '0' || s.charAt(i) > '9') {
            return 0;
        }
        if(i >= s.length()) {
            return 0;
        }
        int res = 0;
        while(i < s.length()) {
            char c = s.charAt(i++);
            if(c >= '0' && c <= '9') {
                int bit = c - '0';
                int temp = 0;
                if(flag) {
                    temp = res * 10 + bit;
                    if((temp-bit) / 10 != res || temp < 0) {
                        return Integer.MAX_VALUE;
                    }
                } else {
                    temp = res * 10 - bit;
                    if((temp + bit) / 10 != res || temp > 0) {
                        return Integer.MIN_VALUE;
                    }
                }
                res = temp;
            } else {
                break;
            }
        }
        return res;
    }
}